<?php

namespace App\Http\Middleware;

use App\Models\BookHomeManageShop;
use App\Models\Manage;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/**
 * 验证后台管理员token
 */
class CheckAdminHeaderToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $app_expire_time = config('other.app_expire_time');
        if ($app_expire_time && $app_expire_time < date('Y-m-d')) {
            $app_expire_msg = config('other.app_expire_msg') ? config('other.app_expire_msg') : '试用已过期！';
            return  response()->json(['code' => 301, 'msg' => $app_expire_msg]); //使用过期，什么都不能使用
        }

        // $request->manage_id = 1;
        // return $next($request);

        $manage_token = $this->getToken($request);

        // if ($manage_token == 'cdbottle123') {
        //     $request->manage_id = 1;
        //     return $next($request);
        // }

        if (empty($manage_token)) {
            return  response()->json(['code' => 205, 'msg' => 'token无效']);
        }

        //验证token有效期
        $manage_info = Manage::where('token', $manage_token)->where('is_del', 1)->first();
        if (empty($manage_info)) {
            return  response()->json(['code' => 205, 'msg' => 'token无效']);
        }
        if ($manage_info->expire_time < date('Y-m-d H:i:s')) {
            return  response()->json(['code' => 205, 'msg' => '登录已过期，请重新登录']);
        }
        //刷新token过期时间
        $manage_info->expire_time = date("Y-m-d H:i:s", (time() + config('other.admin_token_refresh_time')));
        $manage_info->save();
        $request->manage_id = $manage_info->id;

        //获取管辖书店
        // $shop_id = BookHomeManageShop::where('manage_id', $manage_info->id)->pluck('shop_id')->toArray();
        // $manage_info['shop_id'] = $shop_id;

        $request->manage_info = $manage_info;

        return $next($request);
    }

    /**
     * 获取请求参数中的 token
     * @param request  object 请求参数对象
     */
    public function getToken($request)
    {
        // $token = str_replace('Bearer ', '', $request->header('authorization'));

        // if (!$token) {
        //     $token = $request->token;
        // }

        $token = str_replace('Bearer ', '', $request->header('authorization')); //只能从header头获取
        //特殊情况放在链接里面
        $uri = Route::current()->uri;
        if (empty($token) && in_array($uri, [
            // 'admin/pictureLiveWorks/downloadWorksImg', //下载图片直播链接
            // 'admin/competiteActivityWorks/downloadWorksAll', //批量下载大赛作品资源
            // 'admin/competiteActivityWorksExport/index', //单个下载大赛作品资源
            // 'admin/competiteActivityWorks/downloadWorks', //单个下载大赛作品资源
        ])) {
            $token = $request->token;
        }
        return $token;
    }
}
